package com.jetpackframework.retrofit.converter;

import android.text.TextUtils;

import androidx.annotation.Nullable;

import com.gwm.annotation.http.FileUpload;
import com.gwm.annotation.http.HTTP;
import com.gwm.annotation.http.Header;
import com.gwm.annotation.http.HeaderString;
import com.gwm.annotation.http.Path;
import com.gwm.annotation.http.Query;
import com.gwm.annotation.http.QueryMap;
import com.gwm.annotation.http.QueryUrl;
import com.gwm.annotation.http.Url;
import com.jetpackframework.http.HttpUtil;
import com.jetpackframework.retrofit.Converter;
import com.zhy.http.okhttp.builder.PostFormBuilder;

import java.io.File;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.Set;

public class PostFromRequestConverter extends HttpRequestConverter<PostFormBuilder> {
    private static Converter converter;
    public static synchronized Converter get(){
        if (converter == null){
            converter = new PostFromRequestConverter();
        }
        return converter;
    }
    private PostFromRequestConverter(){}
    @Nullable
    @Override
    public PostFormBuilder convert(Method method,Object[] args){
        PostFormBuilder builder = new PostFormBuilder();
        initHttpBasicInfo(method,args,builder);
        Annotation[][] annotations = method.getParameterAnnotations();
        for (int i = 0; i < annotations.length; i++) {     //i:第几个参数的注解
            if (annotations[i].length > 0) {
                for (int j = 0; j < annotations[i].length; j++) {  //j: 第i个参数上的第j个注解
                    if(annotations[i][j] instanceof Query) {
                        Query query = (Query) annotations[i][j];
                        String key = query.value();
                        Object value = args[i];
                        builder.addParams(key,String.valueOf(value));
                    }else if(annotations[i][j] instanceof FileUpload){
                        FileUpload fileUpload = (FileUpload) annotations[i][j];
                        String key = fileUpload.value();
                        File file = (File) args[i];
                        builder.addFile(key,file.getName(),file);
                    }else if (annotations[i][j] instanceof QueryMap){
                        Map paramMap = (Map) args[i];
                        Set<String> keySet = paramMap.keySet();
                        for (String key : keySet){
                            Object value = paramMap.get(key);
                            if (value instanceof File){
                                builder.addFile(key,((File) value).getName(), (File) value);
                            }else {
                                builder.addParams(key,String.valueOf(value));
                            }
                        }
                    }
                }
            }
        }
        return builder;
    }
}
